package com.eva.androidlibrary.utils;

import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

/**
 * Class description
 *
 * @author GUXIA318
 * @date 2015-09-23 15:52
 */
public class FileUtil {

    /**
     * 获取外部指定文件夹路径
     *
     * @param context
     * @return
     */
    public static String getExternalStorageDirectory(Context context) {
        if (null == getExternalStorageDirectory()) {
            return context.getCacheDir().getAbsolutePath();
        }

        File file = new File(getExternalStorageDirectory() + File.separator + context.getPackageName());
        if (!file.exists()) {
            file.mkdir();
        }

        DevUtil.v("Eva", "getExternalStorageDirectory:" + file.getAbsolutePath());
        return file.getAbsolutePath();
    }

    /**
     * get SDPath, if no sdcard, return null
     *
     * @return
     */
    private static String getExternalStorageDirectory() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            return Environment.getExternalStorageDirectory().toString();
        } else {
            Log.e("SDCard", "no sdcard found!");
            return null;
        }
    }

    /**
     * 获取缓存目录
     * 该目录主要用于存放缓存文件，当系统的内存存储空间紧张时，该目录下的文件会被删除。
     *
     * @param context
     * @return
     */
    public static String getCacheDir(Context context) {
        return context.getCacheDir().getAbsolutePath();
    }

    public static String getFileDir(Context context) {
        return context.getFilesDir().getAbsolutePath();
    }

    public static String read(File file) {
        FileInputStream fis = null;
        String result = "";
        try {
            fis = new FileInputStream(file);
            int size = fis.available();
            byte[] buffer = new byte[size];
            fis.read(buffer);
            result = new String(buffer);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fis != null) {
                    fis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    public static void write(File file, String str) {
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file, false);
            fos.write(str.getBytes());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void write(File file, FileInputStream fis) {
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
            byte buffer[] = new byte[1024 * 1024];
            int len;
            while ((len = fis.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
            }
            fos.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }

                if (fis != null) {
                    fis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    /**
     * 从文档URI中获取文档的id
     *
     * @param documentUri
     * @return
     */
    private static String getDocumentId(Uri documentUri) {
        final List<String> paths = documentUri.getPathSegments();
        if (paths.size() >= 2 && "document".equals(paths.get(0))) {
            return paths.get(1);
        }
        if (paths.size() >= 4 && "tree".equals(paths.get(0))
                && "document".equals(paths.get(2))) {
            return paths.get(3);
        }
        throw new IllegalArgumentException("Invalid URI: " + documentUri);
    }

    /**
     * 从内容URI中获取到媒体的id
     *
     * 该方法会先判断contentUri是否是文档URI，如果是文档URI，
     * 则尝试用文档URI的路径格式进行解析，取到id，如果cotentUri是通用的内容URI，
     * 则使用内容URI的格式进行解析，取到id
     *
     * @param uri 内容URI
     * @return 内容的id，如果取不到id，则为-1
     */
    private static String getDocId(Uri uri) {
        if (uri == null || !"content".equals(uri.getScheme())) {
            throw new  IllegalArgumentException("Uri " + uri + " is invalid");
        }

        String docId;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            // 如果大于KITKAT，直接使用原生API获取
            docId = DocumentsContract.getDocumentId(uri);
        } else {
            // 否则自己解析
            docId = getDocumentId(uri);
        }
        return docId;
    }


    public static String getFilePath(final Context context, final Uri uri) {

        // 如果已是文件路径，直接返回path
        if (uri != null && "file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        String docId = getDocId(uri);
        if (isExternalStorageDocument(uri)) {
            final String[] split = docId.split(":");
            final String type = split[0];

            if ("primary".equalsIgnoreCase(type)) {
                return Environment.getExternalStorageDirectory() + "/" + split[1];
            }
        } else if (isDownloadsDocument(uri)) {
            final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId));
            return getDataColumn(context, contentUri, null, null);
        } else if (isMediaDocument(uri)) {
            final String[] split = docId.split(":");
            final String type = split[0];

            Uri contentUri = null;
            if ("image".equals(type)) {
                contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            } else if ("video".equals(type)) {
                contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            } else if ("audio".equals(type)) {
                contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            }

            final String selection = "_id=?";
            final String[] selectionArgs = new String[]{
                    split[1]
            };

            return getDataColumn(context, contentUri, selection, selectionArgs);
        }
        return null;
    }

    /**
     * Get the value of the data column for this Uri. This is useful for
     * MediaStore Uris, and other file-based ContentProviders.
     *
     * @param context The context.
     * @param uri The Uri to query.
     * @param selection (Optional) Filter used in the query.
     * @param selectionArgs (Optional) Selection arguments used in the query.
     * @return The value of the _data column, which is typically a file path.
     */
    public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {column};
        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                final int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return null;
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is Google Photos.
     */
    public static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }
}
